package com.lby.graduation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lby.graduation.entity.Role;
import com.lby.graduation.entity.User;
import com.lby.graduation.mapper.RoleMapper;
import com.lby.graduation.mapper.UserMapper;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;

    /*根据前端登录页面传入的用户名，查询出数据库对应的用户信息和用户权限，
   把用户信息和权限封装成UserDetails对象，交给SpringSecurity进行身份认证*/

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();//加密工具
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        List<Role> role = roleMapper.selectRoleByUserName(username);
        /*封装用户权限*/
        ArrayList<SimpleGrantedAuthority> roleList = new ArrayList<>();
        /*getRoleName()这个方法将返回此用户的所拥有的权限
         * GrantedAuthority已授予的权限
         * */
        for (int i = 0; i < role.size(); i++) {
            roleList.add(new SimpleGrantedAuthority(role.get(i).getRoleName()));
        }
        if (user != null) {
            /*将用户名、密码、用户权限封装成UserDetails对象*/
          UserDetails userDetails=new org.springframework.security.core.userdetails.User(user.getUsername(),encoder.encode(user.getPassword()),roleList);
            return userDetails;
        } else {
            throw new UsernameNotFoundException("用户不存在");
        }
    }
}
